package com.semidata.trp.monitor.frequency;

import java.util.List;

import com.semidata.rtd.core.datasource.redis.RedisDataSource;
import com.semidata.rtd.core.datasource.redis.RedisDataSourceService;
import com.semidata.rtd.core.executor.TaskExecutor;
import com.semidata.rtd.core.job.Job;
import com.semidata.rtd.core.job.ScheduledTask;
import com.semidata.rtd.core.log.Logger;
import com.semidata.rtd.core.service.ServiceManager;
import com.semidata.trp.frequency.Frequency;
import com.semidata.trp.frequency.FrequencyHandler;
import com.semidata.trp.monitor.config.Config;
import com.semidata.trp.monitor.job.MonitorJobContext;
import com.semidata.trp.monitor.job.MonitorRequest;

public class TaskFrequency extends ScheduledTask<Void, MonitorJobContext> {
	final static Integer EXPIRE = 24 * 60 * 60;
    public TaskFrequency(Job<MonitorJobContext> job, TaskExecutor executor) {
        super(job, executor);
    }

    @Override
    public Void run() {
        MonitorJobContext context = getJob().getJobContext();
        //Logger.log("ERROR", "write frequency start : userid : " + context.getMonitorRequest().getUserId() + " materialid : " + context.getMonitorRequest().getMaterialId());
        try{
        	RedisDataSource datasource = ServiceManager.getService(RedisDataSourceService.class).getDataSource();
        	
        	final String userId = context.getMonitorRequest().getUserId();
        	final List<Integer> materialId = context.getMonitorRequest().getMaterialId();
        	Long time = context.getSession().getTimeStamp();
        	for (final Integer mid : materialId) {
        		Frequency fre = new Frequency(datasource);
        		fre.setWriteHandler(new FrequencyHandler() {
				
        			@Override
        			public void handler(Object o) {
        				// TODO Auto-generated method stub
        				//System.out.println("increment a frequency finished: userid : " + userId + " materialid : " + mid);
        				//System.out.println( "Write frequency finished");
        			}
			        		
        		});
        	
        		fre.write(userId, mid.toString(), time.toString(), Config.getConfig().getRedisTaskTimeout());
        		fre.writeExpire(userId, EXPIRE, Config.getConfig().getRedisTaskTimeout());
        	}
        } catch(Exception e) {
        	Logger.log("DEBUG", "error occurs when write frequency");
            Logger.log("ERROR", e);
            throw new RuntimeException(e);
        }
        
        return null;
    }

    @Override
    protected void done(Void result, Throwable cause) throws Exception {
    }

}
